<?php
App::uses( 'CakeEmail', 'Network/Email' );

class MailtokindleShell extends Shell {
	var $uses = array ('Queue' );
	var $email = 0;
	
	function startup() {
		$this->email = & new CakeEmail ( 'gmail' );
	}
	
	function main() {
		
		$queues = $this->Queue->find ( 'all', 
			array (
				'conditions' => array ('Queue.send_time' => null ), 
				'order' => array ('Queue.id' ) 
			) 
		);
		
		if (count ( $queues ) > 0) {
			echo "There is " . count($queues) . "waiting for sending.\r\n";	
			foreach ( $queues as $q ) {
				$this->email->from('book@lupinlin.com');
				$this->email->to( $q['Queue'] ['mail']);
				$this->email->subject($q ['Queue'] ['title']);
				$this->email->replyTo('book@lupinlin.com');
				$this->email->template('simple');
				$this->email->emailFormat('text');
				
				if( !file_exists($q['Queue']['file']))
					echo "File not found";
					
				$this->email->attachments(array ($q['Queue'] ['file']));
				
				echo "No. " . $q['Queue']['id'] . ' is sending...\r\n';
				$this->email->send ();
				
				if (isset ( $this->email->smtpError ) && strlen ( $this->email->smtpError ) > 0)
					echo "Error when sending No." . $q['Queue']['id'] .":". $this->email->smtpError . "\r\n";
				else {
					$q ['Queue'] ['send_time'] = date ( "Y-m-d H:i:s" );
					$this->Queue->save ( $q );
					echo 'No' . $q ['Queue'] ['id'] . ' is sent!\r\n';
				}
			
			}
			
		}
	}
}
?>